package server;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;

import org.apache.commons.math3.stat.Frequency;

import ocsf.server.ConnectionToClient;
/**
 * this class implemnts thred that calculated statistics once a month
 * @author Ron Shenkerman
 * @author Gabi Revah
 * @author Aviad Almog
 * @author Ivan Onyshchenko
 */
public class LendReportMonth implements Runnable{
	
	private ConnectionToClient client;
	private static final long OneWeek = 86400000*7;
	
	private ArrayList<Integer> countwnated= new ArrayList<Integer>();
	private double wantedavg;
	private double wantedemid;
	private Frequency wantedfreq;
	
	private ArrayList<Integer> countnormal= new ArrayList<Integer>();
	private double normalavg;
	private double normalmid;
	private Frequency normalfreq;
	static int row;
	int temp;
	@Override
	/**
	 * run the thred 
	 */
	public void run() {
		
     while(EchoServer.echoserveron){
			
			try 
				{
				SQLConnection conn = new  SQLConnection();
				Statement stmt;	
				stmt = conn.getConnection().createStatement();	
				ResultSet rssss= stmt.executeQuery("SELECT * FROM db1.LendReportMonth;");
				row=1;
				while(rssss.next()){
					temp=rssss.getInt(1);
						if(row>temp)
							row=row;
							else{
							row=temp;
							}	
				}
			
			PreparedStatement ps1 = conn.getConnection().prepareStatement("SELECT wantedday FROM db1.lendReport");
			PreparedStatement ps4 = conn.getConnection().prepareStatement("SELECT normalday FROM db1.lendReport");
			PreparedStatement ps5 = conn.getConnection().prepareStatement("INSERT INTO  LendReportMonth (id,avgwanted,midwanted,avgnormal,midnormal,date) VALUES (?,?,?,?,?,?)");
			java.sql.ResultSet rs =  ps1.executeQuery();
			try {
				while(rs.next())
				{
					countwnated.add((rs.getInt(1)));
										
				}
				wantedavg=calcAvarage(countwnated);
				//System.out.println(wantedavg);
				wantedemid=calcMedian(countwnated);
				//System.out.println(wantedemid);
				wantedfreq=calcFreq(countwnated);
				//System.out.println(wantedfreq);
				java.sql.ResultSet rs1 =  ps4.executeQuery();
				while(rs1.next())
				{
					countnormal.add((rs1.getInt(1)));
										
				}
				normalavg=calcAvarage(countnormal);
				//System.out.println(normalavg);
				normalmid=calcMedian(countnormal);
				//System.out.println(normalmid);
				normalfreq=calcFreq(countnormal);
				//System.out.println(normalfreq);
				ps5.setInt(1, row+1);
				ps5.setDouble(2, wantedavg);
				ps5.setDouble(3, wantedemid);
				ps5.setDouble(4, normalavg);
				ps5.setDouble(5, normalmid);
				java.util.Date today = new java.util.Date();
				java.sql.Date timestamp = new java.sql.Date(today.getTime());
				ps5.setDate(6,timestamp);
				ps5.executeUpdate();
				
				
					  
					
				
							
							
								
							
							
				
				
				}
					catch (SQLException e)
							{	
							e.printStackTrace();
							}
			
				}
			catch (Exception ex )
			{
			ex.printStackTrace();
			}
			
	
			try 
			{
				Thread.sleep(OneWeek);//OneWeek
			
			} 
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
		}
		
	}

	protected double calcAvarage(ArrayList<Integer> list){
		DescriptiveStatistics stat = new DescriptiveStatistics();
		for (Integer x : list){
			stat.addValue(x);
		}
		return stat.getMean();

	}

	protected double calcMedian(ArrayList<Integer> a){		
		Integer[] list = new Integer[a.size()];
	    a.toArray(list);
	    Arrays.sort(list);
	    Collections.sort(a);
	    if (a.size() >0){
	    	if((a.size() % 2) == 0) 
	    		return ( ( a.get(a.size()/2) + a.get(a.size()/2-1) ) / 2);         
	    	return ( a.get(a.size()/2) );   
	    }
	    return 0;
	}

	protected Frequency calcFreq(ArrayList<Integer> a){
		Frequency f = new Frequency();
		for (Integer x : a){
			f.addValue(x);
		}
		return f;

	}









}
